package sz.com.battleship.game;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Random;

import sz.com.battleship.R;
import sz.com.battleship.game.GameElement.GameBoard;
import sz.com.battleship.game.GameElement.Ship;
import sz.com.battleship.game.adapters.gridAdapter;
import sz.com.battleship.game.adapters.shipAdapter;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class ShipPlacementScreen extends Activity implements OnClickListener{
	private Button autoPlace = null;
	private Button finishPlace = null;
	private Button clearPlace = null;
	private ArrayList<HashMap<String, String>> myList;
	private GridView gridview;
	private gridAdapter gridAdapter;
	private shipAdapter shipAdapter;
	
	public GameBoard board;
	
	//Deals with double grid selection
	private int selectedShipType = 0;
	private int selectedPosition1 = 0;
	private int selectedPosition2 = 0; 
	private int selectedCount = 0;
	
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.ship_placement_layout);
	    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	    autoPlace = (Button) findViewById (R.id.buttonAutoPlace);
	    autoPlace.setOnClickListener(this);
	    finishPlace = (Button) findViewById (R.id.buttonFinish);
	    finishPlace.setOnClickListener(this);
	    clearPlace = (Button) findViewById (R.id.buttonClear);
	    clearPlace.setOnClickListener(this);
	    
	    //Game objets initialisation
	    board = new GameBoard();
	    
	    shipAdapter = new shipAdapter(ShipPlacementScreen.this);
	    myList = new ArrayList<HashMap<String, String>>();
        fillMap();
        
        SimpleAdapter shipListAdapter = new SimpleAdapter (this.getBaseContext(), myList, R.layout.list_item,
                new String[] {"img", "title", "description", "size"}, new int[] {R.id.img, R.id.title, R.id.description,R.id.Size});

	    ListView shipList = (ListView) findViewById(R.id.shipList);
	    shipList.setAdapter(shipListAdapter);
	    shipList.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Toast.makeText(ShipPlacementScreen.this, "This is ship :" + position, Toast.LENGTH_SHORT).show();
                selectedShipType = position;
            }
        });
	    
	    gridAdapter= new gridAdapter(ShipPlacementScreen.this);
	    gridview = (GridView) findViewById(R.id.MyGrid);
    	gridview.setAdapter(gridAdapter);
    	gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            	if (!board.shipCanBeAdded(selectedShipType))
            	{
            		Toast.makeText(ShipPlacementScreen.this, "Cannot add any more ship of type : " + Ship.getName(selectedShipType), Toast.LENGTH_SHORT).show();
            	}
            	else if (selectedCount == 0)
            	{
            		if (board.hasShip(position))
            		{
            			Toast.makeText(ShipPlacementScreen.this, "There is already a ship at :" + position, Toast.LENGTH_SHORT).show();
                		View v1 = gridview.getChildAt(selectedPosition1);
                		v1.setBackgroundColor(0);
            			selectedPosition1 = selectedPosition2 = 0;
            			selectedCount = 0;
            		}
            		else
            		{
            			selectedPosition1 = position;
            			v.setBackgroundColor(Color.CYAN);
            			selectedCount++;
            		}
            	}
            	else if (selectedCount == 1)
            	{
            		if (board.hasShip(position))
            		{
            			Toast.makeText(ShipPlacementScreen.this, "There is already a ship at :" + position, Toast.LENGTH_SHORT).show();
                		View v1 = gridview.getChildAt(selectedPosition1);
                		v1.setBackgroundColor(0);
            			selectedPosition1 = selectedPosition2 = 0;
            			selectedCount = 0;
            		}
            		else if (position == selectedPosition1)
            		{
            			//If the user try to reselect the same node, do nothing
            		}
            		else
            		{
            			selectedPosition2 = position;
            			if (board.placeShip(selectedPosition1, selectedPosition2, selectedShipType))
            			{ //If a ship has succesfully been placed with these positions 
            				//Colorgrid by calling putShip
            				//Toast.makeText(ShipPlacementScreen.this, "true", Toast.LENGTH_SHORT).show();
                    		View v1 = gridview.getChildAt(selectedPosition1);
                    		v1.setBackgroundColor(0);
                			selectedPosition1 = selectedPosition2 = 0;
                			selectedCount = 0;
                			
                			//Color the ship cases with the appropriate pictures
                			displayShip(board.getShip(position));
            			}
            			else
            			{
            				Toast.makeText(ShipPlacementScreen.this, "You cannot place this ship here", Toast.LENGTH_SHORT).show();
            			}
                		View v1 = gridview.getChildAt(selectedPosition1);
                		v1.setBackgroundColor(0);
            			selectedPosition1 = selectedPosition2 = 0;
            			selectedCount = 0;
            		}
            	}
            	else
            	{
            		//Reset grid selection if this state is somehow achieved
            		View v1 = gridview.getChildAt(selectedPosition1);
            		v1.setBackgroundColor(0);
            		selectedCount = 0;
            		selectedPosition1 = 0;
            		selectedPosition2 = 0;
            	}
            	/*gridview.setSelection(position);
                Toast.makeText(ShipPlacementScreen.this, "Selected: " + position, Toast.LENGTH_SHORT).show();
                putShip(v);*/
            }
        });
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.buttonAutoPlace)
		{
			autoPlacement();
		}
		else if (v.getId() == R.id.buttonFinish ){
			if(isAllShipPlaced()){
				Intent myIntent = getIntent();
				myIntent.putExtra("GameBoard",board);
	
				setResult(1, myIntent);
				finish();
			}
			else{
				Toast.makeText(this, "All ships must be placed", Toast.LENGTH_SHORT).show();
			}
		}
		else if (v.getId() == R.id.buttonClear ){
			board.clearBoard();
			removeAllShips();
		}		
	}
	private boolean isAllShipPlaced(){
		for(int type = 0; type < 5;type++)
		{
			if (board.shipCanBeAdded(type))
			{ 
				return false;
			}
		}
		return true;
	}
	
	private void autoPlacement(){
		board.clearBoard();
		removeAllShips();
		Random randomGenerator = new Random(System.nanoTime());
		for(int type = 0; type <= 4;type++)
		{
			boolean placed = false; //ship has not been placed yet
			while(!placed)
			{
				if (!board.shipCanBeAdded(type))
				{ //All ships of current type have been added successfully
					placed = true;
				}
				else
				{
					int newPosition = randomGenerator.nextInt(GameBoard.BOARD_SIZE);
					ArrayList<Integer> shuffleList = new ArrayList<Integer>(); //shuffle list used to randomly determine the orientation attempts when placing ship
					
					//adding all possible orientation
					if (newPosition + (Ship.getSize(type) - 1) < 100) {shuffleList.add(newPosition + (Ship.getSize(type) - 1));}
					if (newPosition - (Ship.getSize(type) - 1) >= 0) {shuffleList.add(newPosition - (Ship.getSize(type) - 1));}
					if (newPosition + (10 * (Ship.getSize(type) - 1)) < 100) {shuffleList.add(newPosition + (10 * (Ship.getSize(type) - 1)));}
					if (newPosition - (10 * (Ship.getSize(type) - 1)) >= 0) {shuffleList.add(newPosition - (10 * (Ship.getSize(type) - 1)));}
					
					//Shuffling them
					Collections.shuffle(shuffleList, randomGenerator);
					
					for(int newPosition2 : shuffleList)
					{
						if (board.placeShip(newPosition, newPosition2, type))
						{
							displayShip(board.getShip(newPosition));
							break;
						}
					}
				}
			}
		}
	}
	
	//Color the nodes of a ship with the picture of the appropriate ship
	private void displayShip(Ship ship){
		if (ship != null)
		{
			for(int current : ship.getBoardSpaces_())
			{
				ImageView view = (ImageView) gridview.getChildAt(current);
				view.setImageResource((Integer) shipAdapter.getItem(ship.getType()));
			}
		}
		else
		{
			Toast.makeText(ShipPlacementScreen.this, "Could not display the new ship", Toast.LENGTH_SHORT).show();
		}
	}
	
	//Remove the image of all ships from the board
	private void removeAllShips()
	{
		for(int i = 0; i < GameBoard.BOARD_SIZE;i++)
		{
			ImageView view = (ImageView) gridview.getChildAt(i);
			view.setImageResource(android.R.color.transparent);
		}
	}
	
	private void fillMap(){
		HashMap<String, String> map;
        map = new HashMap<String, String>();
        map.put("title", "BattleCruser");
        map.put("description", "Large Terran Ship");
        map.put("size", "5 Blocks");
        map.put("img", String.valueOf(R.drawable.battlecruser));
        myList.add(map);
        
        map = new HashMap<String, String>();
        map.put("title", "Carrier");
        map.put("description", "Large Protoss Ship");
        map.put("size", "4 Blocks");
        map.put("img", String.valueOf(R.drawable.carrier));
        myList.add(map);
        
        map = new HashMap<String, String>();
        map.put("title", "Medivac");
        map.put("description", "Terran Transport Ship");
        map.put("size", "3 Blocks");
        map.put("img", String.valueOf(R.drawable.medivac));
        myList.add(map);
        
        map = new HashMap<String, String>();
        map.put("title", "Phoenix");
        map.put("description", "Protoss Tactical Ship");
        map.put("size", "3 Blocks");
        map.put("img", String.valueOf(R.drawable.phoenix));
        myList.add(map);
        
        map = new HashMap<String, String>();
        map.put("title", "Viking");
        map.put("description", "Terran Spy Ship");
        map.put("size", "2 Blocks");
        map.put("img", String.valueOf(R.drawable.viking));
        myList.add(map);
	}
}
